﻿using NfsCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace NfsCommon.WeChartHelper
{
   public class GetTokenAndTinket 
    {
        private int number = 0;
        public string GetConfig(string AddressUrl, string createNonceStr)
        {
            string httpPath = AddressUrl;
            var appid = "wx5321dac9999dbb9e";
            var client = new System.Net.WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var url = string.Empty;
            url = string.Format("http://t.comfotxi.com/token/?act=token");
            var access_token = client.DownloadString(url);
            Jsapi_ticket jt = new Jsapi_ticket();
            if (CookieHelper.GetValue("jsapi_ticket") == string.Empty)
            {
                url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);
                var jsapi_ticket = client.DownloadString(url);
                jt = jss.Deserialize<Jsapi_ticket>(jsapi_ticket);
                CookieHelper.Save("jsapi_ticket", jt.ticket, 1.9);
            }
            string jsapiTicket = CookieHelper.GetValue("jsapi_ticket").ToString();
            var urlpath = httpPath;
            string timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
            //时间戳
            string nonceStr = createNonceStr;
            // 这里参数的顺序要按照 key 值 ASCII 码升序排序 
            string rawstring = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + urlpath + "";
            Wx_Config wc = new Wx_Config
            {
                appId = Convert.ToString(appid),
                signature = SHA1_Hash(rawstring),
                nonceStr = nonceStr,
                timestamp = Convert.ToInt32(timestamp)
            };
            return jss.Serialize(wc).ToString();
        }

        //SHA1哈希加密算法 
        public string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
            return str_sha1_out;
        }

        /// <summary> 
        /// 将c# DateTime时间格式转换为Unix时间戳格式 
        /// </summary>
        /// <param name="time">时间</param> 
        /// <returns>时间</returns> 
        public int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = Convert.ToInt32((time - startTime).TotalSeconds);
            return intResult;
        }

        public class Jsapi_ticket
        {
            public int errcode { get; set; }
            public string errmsg { get; set; }
            public string ticket { get; set; }
            public int expires_in { get; set; }
        }
        //appId: '', // 必填，公众号的唯一标识
        //timestamp: , // 必填，生成签名的时间戳
        //nonceStr: '', // 必填，生成签名的随机串
        //signature: '',// 必填，签名，见附录1
        //例如：
        //appId: 'wxf8b4f85f3a794e77',
        //timestamp: 1421142450,
        //nonceStr: '9hKgyCLgGZOgQmEI',
        //signature: 'bf7a5555f9ad0e7e491535f232349a40510a6f8f',
        public class Wx_Config
        {
            public string appId { get; set; }
            public int timestamp { get; set; }
            public string nonceStr { get; set; }
            public string signature { get; set; }
        }
    }
}